package com.example.controller;

import com.example.service.SysUserService;
import com.example.utils.RedisUtils;
import com.example.utils.Result;
import com.example.utils.SecurityUtils;
import com.example.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;


/**
 * TODO
 * 登录、退出、获取当前登录用户相关信息接口
 * @Comment：最难的一次作业
 * @Date: 2023/11/18
 */
@Api(tags = "用户使用接口")
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        return userService.login(loginVo);
    }

    @ApiOperation(value = "获取当前用户的基本信息")
    @GetMapping("/getInfo")
    public Result getUserInfo() {
        return  Result.success("获取用户信息成功！", SecurityUtils.getUser());
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public Result logout() {
        // 清空redis缓存
        redisUtils.delValue("userInfo_" + SecurityUtils.getUsername());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        return Result.success("退出成功！");
    }
}
